<?php

class UtilityController extends CustomControllerAction {

    public function captchaAction() {
        $session = new Zend_Session_Namespace('captcha');

        // проверим, есть ли уже фраза в сессии
        $phrase = null;
        if (isset($session->phrase) && strlen($session->phrase) > 0)
            $phrase = $session->phrase;

        $count = 5;
        $width = 120;
        $height = 60;
        $font_size_min = 32;
        $font_size_max = 32;
        $font_file = Zend_Registry::get('config')->paths->data . "/Comic_Sans_MS.ttf";
        $char_angle_min = -10;
        $char_angle_max = 10;
        $char_angle_shadow = 5;
        $char_align = 40;
        $start = 5;
        $interval = 16;
        $chars = "0123456789";
        $noise = 10;

        $image = imagecreatetruecolor($width, $height);

        $background_color = imagecolorallocate($image, 255, 255, 255);
        $font_color = imagecolorallocate($image, 32, 64, 96);

        imagefill($image, 0, 0, $background_color);

        $str = "";

        $num_chars = strlen($chars);
        for ($i = 0; $i < $count; $i++) {
            $char = $chars[rand(0, $num_chars - 1)];
            $font_size = rand($font_size_min, $font_size_max);
            $char_angle = rand($char_angle_min, $char_angle_max);
            imagettftext($image, $font_size, $char_angle, $start, $char_align, $font_color, $font_file, $char);
            imagettftext($image, $font_size, $char_angle + $char_angle_shadow * (rand(0, 1) * 2 - 1), $start, $char_align, $background_color, $font_file, $char);
            $start+=$interval;
            $str.=$char;
        }

        if ($noise) {
            for ($i = 0; $i < $width; $i++) {
                for ($j = 0; $j < $height; $j++) {
                    $rgb = imagecolorat($image, $i, $j);
                    $r = ($rgb >> 16) & 0xFF;
                    $g = ($rgb >> 8) & 0xFF;
                    $b = $rgb & 0xFF;
                    $k = rand(-$noise, $noise);
                    $rn = $r + 255 * $k / 100;
                    $gn = $g + 255 * $k / 100;
                    $bn = $b + 255 * $k / 100;
                    if ($rn < 0)
                        $rn = 0;
                    if ($gn < 0)
                        $gn = 0;
                    if ($bn < 0)
                        $bn = 0;
                    if ($rn > 255)
                        $rn = 255;
                    if ($gn > 255)
                        $gn = 255;
                    if ($bn > 255)
                        $bn = 255;
                    $color = imagecolorallocate($image, $rn, $gn, $bn);
                    imagesetpixel($image, $i, $j, $color);
                }
            }
        }

        // запишем фразу в сессию
        $session->phrase = $str;

        // отключим авторендеринг, так как нам нужно вывести изображение
        $this->_helper->viewRenderer->setNoRender();

        if (function_exists("imagepng")) {
            header("Content-type: image/png");
            imagepng($image);
        } elseif (function_exists("imagegif")) {
            header("Content-type: image/gif");
            imagegif($image);
        } elseif (function_exists("imagejpeg")) {
            header("Content-type: image/jpeg");
            imagejpeg($image);
        }
    }

    /*   public function getcity1Action() {
      $term = trim($_POST['value']);

      //$term = $_POST[term];
      $countr = $this->getRequest()->getPost('countr');
      $url = 'https://api.vk.com/method/database.getCities?country_id=' . urlencode($countr) . '&q=' . urlencode($term) . '&need_all=0&v=5.16&count=1000';

      // обращаемся к API и декодируем результат
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($ch, CURLOPT_HEADER, false);
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_REFERER, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
      $translate = curl_exec($ch);
      curl_close($ch);
      $json = json_decode($translate, true);


      foreach ($json['response']['items'] as $item) {
      $found[] = array(
      "value" => $item['title'],
      );
      }

      // JSON encode the array for return
      $this->sendJSON($found);
      } */

    public function getcityAction() {

        $region_id = @intval($_GET['region_id']);

        $result = CustomControllerAction::getCity($region_id);
        $this->sendJSON($result);
    }

    public function getregionAction() {

        $country_id = @intval($_GET['country_id']);

        $result = CustomControllerAction::getRegion($country_id);

        $this->sendJSON($result);
    }
     public function getcatsAction() {

        $cats = @intval($_GET['cats']);

        $cat = DatabaseObject_Categories::GetCatsSelect($this->db, $cats);
         if ($cat) {
            $result = array('cat' => $cat);
        } else {
            $result = array('type' => 'error');
        }
       // CustomControllerAction::pre($result);
        $this->sendJSON($result);
    }

    public function autocityAction() {
        $a_json = array();
        $q = $this->getRequest()->getParam('term');
        $query = "SELECT * FROM `geo_cities` LEFT JOIN `geo_regions` ON `rid`=`region_id`  LEFT JOIN `geo_countries` ON `geo_regions`.`cid`=`country_id` WHERE `city_name` LIKE '$q%' ORDER BY `city_name` ASC LIMIT 5";
        $result = $this->db->fetchAll($query);
        foreach ($result as $k => $v) {
            $kk['id'] = $v['city_id'];
            $kk['value'] = $v['city_name'] . "," . $v['country_name'];
            array_push($a_json, $kk);
        }
        CustomControllerAction::sendJSON($a_json);
        exit;
    }

    public function tfAction() {
        $this->view->dialogs = DatabaseObject_Pm::GetUserDialogs($this->db, 3, 10, 0);
    }

    public function loginzaAction() {
        $token = $this->getRequest()->getPost('token');
        $id = Zend_Registry::get('config')->loginza->id;
        $sid = md5($token . Zend_Registry::get('config')->loginza->sid);

        $query = sprintf('http://loginza.ru/api/authinfo?token=%s&id=%s&sig=%s', $token, $id, $sid
        );

        $data = json_decode(file_get_contents($query));
        //$this->pre($data);
        // дальше тут будет немерянно кода по упрощенной авторизации

        $user = new DatabaseObject_User($this->db);
        //$user->load(1);

        if ($user->load($data->identity, 'from_sn')) {
            // пользователь ранее уже логинился через соцсети, просто впустим его

            $auth = Zend_Auth::getInstance();
            $identity = $user->createAuthIdentity();
            $auth->getStorage()->write($identity);
            $user->date_last = date('Y-m-d H:i:s');
            $user->save();
            $message = sprintf('Успешная авторизация пользователя  %s', $user->login);
            $this->writeLog($message);
            foreach ($_SESSION['cart'] as $k => $v)
                foreach ($v as $kk => $vv)
                    CustomControllerAction::SessionFormDb($kk, $vv);
            unset($_SESSION['cart']);
            // вернем пользователяна исходную страницу
            $this->_redirect($this->getUrl('index', 'index'));
        } else {
            switch ($data->provider) {
                case 'http://vk.com/':
                    $user->first_name = $data->name->first_name . " " . $data->name->last_name;
                    $user->login = $data->uid;
                    $user->password = md5($data->uid);
                    $user->email = 'не указано';
                    break;
                case 'http://odnoklassniki.ru/':
                    $user->first_name = $data->name->full_name;
                    $user->login = $data->uid;
                    $user->password = md5($data->uid);
                    $user->email = 'не указано';
                    break;
                case 'http://www.facebook.com/':
                    $user->first_name = $data->name->full_name;
                    $user->login = $data->uid;
                    $user->password = md5($data->uid);
                    $user->email = $data->email;
                    break;
                case 'http://mail.ru/':
                    $user->first_name = $data->nickname;
                    $user->login = $data->uid;
                    $user->password = md5($data->uid);
                    $user->email = $data->email;
                    break;
                case 'http://twitter.com':
                    $user->first_name = $data->name->first_name . " " . $data->name->last_name;
                    $user->login = $data->uid;
                    $user->password = md5($data->uid);
                    $user->email = 'не указано';
                    break;
                case 'https://www.google.com/accounts/o8/ud':
                    $user->first_name = $data->name->first_name . " " . $data->name->last_name;
                    $user->login = $data->email;
                    $user->password = md5($data->email);
                    $user->email = $data->email;
                    break;
            }

            $user->country_id = 0;
            $user->region_id = 0;
            $user->city_id = 0;
            $user->type = 'member';
            $user->isApproved = 0;
            $user->phone = 'не указано';
            $user->from_sn = $data->identity;



            $user->save();

            $auth = Zend_Auth::getInstance();
            $identity = $user->createAuthIdentity();
            $auth->getStorage()->write($identity);
            $user->date_last = date('Y-m-d H:i:s');
            $user->save();
            $message = sprintf('Успешная авторизация пользователя  %s', $user->login);
            $this->writeLog($message);
            foreach ($_SESSION['cart'] as $k => $v)
                foreach ($v as $kk => $vv)
                    CustomControllerAction::SessionFormDb($kk, $vv);
            unset($_SESSION['cart']);
            // вернем пользователяна исходную страницу
            $this->_redirect($this->getUrl('index', 'index'));
        }
    }

    public function testimgAction() {
        $this->pre(getimagesize('http://daba.hm/uploads/1397031530.png'));
    }

    public function activateAction() {
        $hash = $this->getRequest()->getQuery('hash');

        $user = new DatabaseObject_User($this->db);
        if (!$user->load($hash, 'hash')) {
            $this->view->error = true;
        } else {
            $user->isApproved = 1;
            $user->save();
            $this->view->error = false;
        }
    }

}

?>
